<?php
/**
 *   Run all the testcase found in the file
 *   which include the runner.
 */

//error_reporting(0);

if(!defined('QSTONE_DIR')){
    define('QSTONE_DIR',dirname(__FILE__));
}

function __autoload($class_name){
    $path = strtolower(str_replace("_","/",$class_name));
    $path = QSTONE_DIR.'/'.$path.".php";
    if(file_exists($path)){
        require_once($path);
    }
}

$GLOBALS['QSTONETEST_AUTORUNNER_INITIAL_CLASSES'] = get_declared_classes();
register_shutdown_function('runTest');

/**
 *    Exit handler to run all recent test cases and exit system if in CLI
 */
function runTest() {
    $result = run_local_tests();
    if (QStone_Context::inCli()) {
        exit($result ? 0 : 1);
    }
}

function run_local_tests() {
    try {
        $candidates = capture_new_classes();
        $loader = QStone_FileLoader::getLoader();
        $suite = $loader->createSuiteFromClasses(
                basename(initial_file()),
                $loader->selectRunnableTests($candidates));
        return $suite->run(Reporter_Factory::getReporter());
    } catch (Exception $stack_frame_fix) {
        print $stack_frame_fix->getMessage();
        return false;
    }
}

/**
 *    The first autorun file.
 *    @return string        Filename of first autorun script.
 */
function initial_file() {
    static $file = false;
    if (! $file) {
        if (isset($_SERVER, $_SERVER['SCRIPT_FILENAME'])) {
            $file = $_SERVER['SCRIPT_FILENAME'];
        } else {
            $included_files = get_included_files();
            $file = reset($included_files);
        }
    }
    return $file;
}

/**
 *    Every class since the first autorun include. This
 *    is safe enough if require_once() is always used.
 *    @return array        Class names.
 */
function capture_new_classes() {
    global $QSTONETEST_AUTORUNNER_INITIAL_CLASSES;
    return array_map('strtolower', array_diff(get_declared_classes(),
                            $QSTONETEST_AUTORUNNER_INITIAL_CLASSES ?
                            $QSTONETEST_AUTORUNNER_INITIAL_CLASSES : array()));
}
?>
